package com.dios.mirage.component;

import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class Managers extends VerticalFieldManager {

	int posY = 0;
	int current = 0;
	int recent = 0;
	int edge;
	int pos;
	boolean move = false;
	public long speed = 10;
	private boolean loop;
	public long delay = 10000;

	public Managers(BitmapField[] fields) {
		addAll(fields);
		Thread thread = new AnimationThread(this);
		thread.start();
	}

	protected void sublayout(int maxWidth, int maxHeight) {
		int fieldWidth;
		int fieldHeight = 0;
		for (int i = 0; i < getFieldCount(); i++) {
			edge = getField(i).getPreferredWidth();
			pos = edge;
			fieldWidth = getField(i).getPreferredWidth();
			fieldHeight = getField(i).getPreferredHeight();
			layoutChild(getField(i), fieldWidth, fieldHeight);
			setPositionChild(getField(i), edge * (i + 1), posY);
		}
		setExtent(edge, fieldHeight);
	}

	protected void subpaint(Graphics graphics) {
		if (move) {
			if(loop){
				setPositionChild(getField(recent), pos, posY);
				loop = false;
			}
			setPositionChild(getField(current), pos -= 50, posY);
			if (pos < 0) {
				setPositionChild(getField(current), 0, posY);
				recent = current;
				current++;
				if (current == 3)current = 0;
				loop = true;
			}
			super.subpaint(graphics);
		}
	}

	private class AnimationThread extends Thread {

		Managers managers;

		public AnimationThread(Managers managers) {
			this.managers = managers;
		}

		public void run() {
			move = true;
			while (true) {
				try {
					if (pos < 0){
						pos = edge;
						sleep(delay );
					}
					UiApplication.getUiApplication().invokeAndWait(
							new Runnable() {
								public void run() {
									managers.invalidate();
								}
							});
					sleep(speed);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		/*
		 * public void run() { }
		 */

	}
}